package mylab.io.store.rxtx;

import com.google.common.collect.Lists;

import java.util.Enumeration;
import java.util.List;

import gnu.io.CommPortIdentifier;
import lombok.experimental.UtilityClass;
import mylab.utils.common.OsUtil;
import mylab.utils.common.ShellUtil;
import mylab.utils.common.StringUtil;

@UtilityClass
public class RxtxUtil {

    /**
     * 获取所有串口名称列表
     */
    public List<String> getSerialPorts() {
        List<String> list = Lists.newArrayList();
        Enumeration<?> allPorts = CommPortIdentifier.getPortIdentifiers();
        while (allPorts.hasMoreElements()) {
            if (allPorts.nextElement() instanceof CommPortIdentifier commPort) {
                list.add(commPort.getName());
            }
        }
        return list;
    }


    public boolean contains(String serialPortName) {
        return getSerialPorts().contains(serialPortName);
    }


    /**
     * 系统授权<p>
     * 在 Linux 或 macOS 上，可能需要为当前用户添加串口访问权限<p>
     * <p>
     * # Linux: 添加用户到 dialout 组<p>
     * sudo usermod -a -G dialout your_username<p>
     * <p>
     * # macOS: 确保串口设备权限正确<p>
     * sudo chmod 666 /dev/tty.usb*<p>
     */
    public void preparePermisson(String serialPortName) {
        System.setProperty("gnu.io.rxtx.SerialPorts", serialPortName);
        String cmd;
        ShellUtil.CommandResult cmdRes;

        if (OsUtil.isLinux() || OsUtil.isMacOS() || OsUtil.isMacOSX()) {
            cmd = String.format("chmod 666 %s", serialPortName);
            cmdRes = ShellUtil.execCommand(cmd, true, true);
            if (StringUtil.isNotEmpty(cmdRes.getErrorMsg())) {
                throw new SecurityException("没有串口读写权限");
            }
        }

        if (OsUtil.isLinux()) {
            cmd = String.format("chmod 777 %s", "/data/local/tmp");
            cmdRes = ShellUtil.execCommand(cmd, true, true);
            if (StringUtil.isNotEmpty(cmdRes.getErrorMsg())) {
                throw new SecurityException("没有android root权限");
            }
        }
    }
}
